/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package edu.gmu.javalution.crowd;

import java.util.Arrays;
import java.util.Collection;

/**
 *
 * @author Jason
 */
public class DoubleArrayNormalizer implements INormalize<double[]>
{

    private double[] minValues = null;
    private double[] maxValues = null;
    private double[] deltaValues = null;

    public void calculateNormalizationFactors(final Collection<double[]> vectors)
    {
        final int vecLength = vectors.iterator().next().length;
        minValues = new double[vecLength];
        maxValues = new double[vecLength];
        deltaValues = new double[vecLength];
        Arrays.fill(minValues, Double.POSITIVE_INFINITY);
        Arrays.fill(maxValues, Double.NEGATIVE_INFINITY);
        for (double[] vector : vectors)
        {
            assert (vector.length == vecLength);
            for (int i = 0; i < vecLength; i++)
            {
                minValues[i] = Math.min(minValues[i], vector[i]);
                maxValues[i] = Math.max(maxValues[i], vector[i]);
            }
        }

        for (int i = 0; i < vecLength; i++)
        {
            deltaValues[i] = maxValues[i] - minValues[i];
        }
    }

    public double[] normalize(final double[] vector)
    {
        if (minValues == null)
        {
            throw new IllegalArgumentException(
                    "Must call calculateNormalizationFactors prior to normalize");
        }
        else
        {
            double[] normalized = new double[vector.length];
            for (int i = 0; i < vector.length; i++)
            {
                normalized[i] = (vector[i] - minValues[i]) / deltaValues[i];
            }
            return normalized;
        }
    }
}
